/**
 * 
 */
package com.gordon.tips.dao;

import java.util.HashMap;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.gordon.tips.domain.User;
import com.gordon.tips.util.MD5;



/**
 *****************************************************************************
 ** Module : User Access Dao
 ** 
 ** Date:  Aug,10th
 ** 
 ** Author: Gordon
 ** 
 ** Email: 462991284@qq.com
 ** 
 ** (C) Copyright 2011 Gordon Office
 *****************************************************************************
 */

public class UserDao extends SqlMapClientDaoSupport 
{
	/**
	 * Register
	 * @param user User to be register
	 * @return
	 * @Author: Gordon
	 */
	public int register(User user) {
		return (Integer) getSqlMapClientTemplate().insert("register", user);
	}

	/**
	 * Check whether name exist
	 * @param name
	 * @return
	 * @Author: Gordon
	 */
	
	public boolean chkIfNameExist(String name) {
		logger.debug("dao works for checking user's name whether duplicates.");
		User user=(User) getSqlMapClientTemplate().queryForObject("chkIfNameExist", name);
		if(user==null||user.getId()==0)return false;
		else return true;
	}

	/**
	 * Check whether email exist
	 * @param email
	 * @return
	 */
	public boolean chkIfEmailExist(String email) {
		User user=(User) getSqlMapClientTemplate().queryForObject("chkIfEmailExist", email);
		if(user==null||user.getId()==0)return false;
		else return true;
	}

	/**
	 * Login by name at dao
	 * @param nameOrEmail
	 * @param user
	 * @return
	 */
	public User loginByName(String nameOrEmail, User user) {
		HashMap<String,String>map=new HashMap<String, String>();
		user.setPassword(new MD5().getMD5ofStr(user.getPassword()));
		map.put("name", nameOrEmail);
		map.put("password", user.getPassword());
		logger.debug("map's name="+nameOrEmail);
		logger.debug("map's password="+user.getPassword());
		User newUser=(User) getSqlMapClientTemplate().queryForObject("loginByName",map);		
		if(newUser==null||newUser.getId()==0)
		{
			logger.debug("newUser is null");
			return null;
		}
			
		return newUser;
	}

	/**
	 *  Login by email at dao
	 * @param nameOrEmail
	 * @param user
	 * @return
	 */
	public User loginByEmail(String nameOrEmail, User user) {
		HashMap<String,String>map=new HashMap<String, String>();
		user.setPassword(new MD5().getMD5ofStr(user.getPassword()));
		map.put("email", nameOrEmail);
		map.put("password", user.getPassword());
		User newUser=(User) getSqlMapClientTemplate().queryForObject("loginByEmail",map);		
		if(newUser==null||newUser.getId()==0)
		{
			logger.debug("newUser is null");
			return null;
		}
			
		return newUser;
	}
	
	public void updatePost(int userId)
	{
		getSqlMapClientTemplate().update("updatePost",userId);
	}
	

}
